package lock;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
 * @author lchenglong
 * @date 2024/2/5
 */
public class SecurityUtils {
    private static Logger logger = LoggerFactory.getLogger(SecurityUtils.class);

    private static final String ivParameter = "0102030405060708";

    public static String encrypt(String content, String password) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] raw = password.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
            return Base64.encodeBase64URLSafeString(encrypted); // 加密
        } catch (Exception e) {
            logger.info("堆栈信息:", e);
        }
        return "";
    }
    public static String decrypt(String content, String password) {
        try {
            byte[] raw = password.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = Base64.decodeBase64(content);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception e) {
            logger.info("堆栈信息:", e);
        }
        return "";
    }

    public static String MD5(String str) {

        return DigestUtils.md5Hex(str);
    }

    public static void main(String[] args) {
        String secret = "123456789ABCDEFG";
        JSONObject object = new JSONObject();
        object.put("stuId",123);
        String data = SecurityUtils.encrypt(JSON.toJSONString(object),secret);
        String Md5 = SecurityUtils.MD5(JSON.toJSONString(object));

        String decryptData = SecurityUtils.decrypt(data,secret);
        String decryptMd5 = SecurityUtils.MD5(decryptData);
        System.out.println(Md5.equals(decryptMd5));
    }
}
